with xpa.io.tio;
with ada.text_io;
with ada.wide_text_io;
with ada.io_exceptions;
with interfaces.c_streams;
with system;

procedure test_tio is

	procedure read_data (
		user_data: in out integer; cmd: in integer; 
		text: out xpa.mstr; last: out natural) is

		c: integer;
	begin
		case cmd is
		when 1 =>
			null;
		when 2 =>
			null;
		when others =>
			last := text'first - 1;
			while last < text'last loop
				c := interfaces.c_streams.fgetc (interfaces.c_streams.stdin);
				if interfaces.c_streams.ferror(interfaces.c_streams.stdin) /= 0 then
					raise ada.io_exceptions.device_error;
				end if;
				if c = -1 then
					if last >= text'first then
						exit;
					else
						raise ada.io_exceptions.end_error;
					end if;
				end if;

				last := last + 1;
				text(last) := xpa.mchar'val(c);

				if text(last) = xpa.MC_NL then
					exit;
				end if;
			end loop;

			--ada.text_io.get_line (text(text'first..text'last-1), last);
			--if last >= text'first then
				-- some data have been read
				--last := last + 1;
			--else
				-- just an empty line
				--last := text'first;
			--end if;
			--text(last) := character'val(10);
		end case;
	end read_data;

	procedure write_data (
		user_data: in out integer; cmd: in integer; 
		text: in xpa.mstr; last: out natural) is
	begin
		case cmd is
		when 1 =>
			null;
		when 2 =>
			null;
		when others =>
			ada.text_io.put (text(text'first..text'first));
			--last := text'last;
			last := text'first;
		end case;
	end write_data;

	package tio is new xpa.io.tio (integer, integer, read_data, write_data);
	use tio;


	t: tio.tio_access := null;
	s: xpa.str (5..20);
	last: natural;

	procedure hello is
		at_end: boolean := false;

	begin

		tio.open (t);

		declare
			length: natural;
		begin
			loop
				tio.get (t, s, last);
				if last >= s'first then
					length := last - s'first + 1;
					--ada.wide_text_io.put ("Length: ");
					--ada.text_io.put_line (length'img);
					--ada.wide_text_io.put ("Input: ");
					--ada.wide_text_io.put_line (s(s'first..last));

					tio.put (t, s(s'first..last));
					--tio.flush (t);
				else
					ada.wide_text_io.put_line (">> no input");
				end if;
			end loop;

			ada.text_io.put_line ("end");

		exception
			when xpa.end_error =>
				null;

			when others =>
				tio.close (t);	
				raise;

		end;

ada.text_io.put_line ("xxxxxxxxxxxxxxxx");
		tio.close (t);


	exception
		when others =>
			--if t /= null then
			--	tio.close (t);	
			--end if;
			ada.text_io.put_line ("OOPS! an exception occurred");
	end hello;

begin
	hello;
end test_tio;
